import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:meco/common/index.dart';
import 'package:meco/common/data/repositories/user_follow_repository.dart';
import 'package:meco/common/data/repositories/chat_room_repository.dart';

// 创建一个全局的路由观察器
final RouteObserver<ModalRoute<void>> routeObserver =
    RouteObserver<ModalRoute<void>>();

class MeController extends GetxController
    with GetSingleTickerProviderStateMixin, RouteAware
    implements
        CeramicInteractionObserver,
        VideoInteractionObserver,
        UserFollowObserver,
        VideoDeleteObserver,
        CeramicDeleteObserver,
        OfficialContentDeleteObserver {
  MeController();

  // 仓库
  final UserRepository _userRepository = UserRepository();
  final UserFollowRepository _userFollowRepository = UserFollowRepository();
  final CeramicRepository _ceramicRepository = CeramicRepository();
  final CeramicInteractionRepository _ceramicInteractionRepository =
      CeramicInteractionRepository();
  final VideoInteractionRepository _videoInteractionRepository =
      VideoInteractionRepository();
  final BrowseRecordRepository _browseRecordRepository =
      BrowseRecordRepository();
  final ChatRoomRepository _chatRoomRepository = ChatRoomRepository();

  // Tab控制器
  late TabController tabController;

  // 当前页面显示的用户
  final Rx<User?> pageUser = Rx<User?>(null);

  // 是否是自己的主页
  final RxBool isOwnProfile = true.obs;

  // 是否从导航栏进入
  final RxBool isFromNavBar = true.obs;

  // 统计数据
  final RxInt followingCount = 0.obs;
  final RxInt followersCount = 0.obs;
  final RxInt groupsCount = 0.obs;
  final RxInt chatCount = 0.obs;

  // 是否已关注该用户
  final RxBool isFollowing = false.obs;

  // 收藏的内容
  final RxList<Ceramic> favoritedCeramics = <Ceramic>[].obs;
  final RxList<RecommendedVideo> favoritedVideos = <RecommendedVideo>[].obs;
  final RxList<OfficialContent> favoritedOfficialContents =
      <OfficialContent>[].obs;

  // 点赞的内容
  final RxList<Ceramic> likedCeramics = <Ceramic>[].obs;
  final RxList<RecommendedVideo> likedVideos = <RecommendedVideo>[].obs;
  final RxList<OfficialContent> likedOfficialContents = <OfficialContent>[].obs;

  // 发布的内容
  final RxList<Ceramic> publishedCeramics = <Ceramic>[].obs;

  // 加载状态
  final RxBool isLoading = false.obs;

  // 用于存储每个内容的浏览用户
  final RxMap<String, RxList<User>> contentViewedUsers =
      <String, RxList<User>>{}.obs;
  final RxMap<String, RxBool> contentUsersLoading = <String, RxBool>{}.obs;

  // 初始化数据
  Future<void> initData() async {
    isLoading.value = true;

    // 检查是否需要强制刷新
    bool forceRefresh = Get.arguments?['forceRefresh'] ?? false;
    if (forceRefresh) {
      print('强制刷新Me页面数据');
    }

    // 获取当前用户服务
    final UserService userService = Get.find<UserService>();

    // 处理从导航栏进入的情况
    if (isFromNavBar.value) {
      // 如果已登录，显示个人主页
      if (userService.isLoggedIn.value) {
        pageUser.value = userService.currentUser.value;
        isOwnProfile.value = true;
        await loadUserData();
      } else {
        // 未登录状态，pageUser为空，显示登录按钮
        pageUser.value = null;
      }
    }
    // 处理从其他地方进入的情况
    else {
      // 从参数中获取用户ID
      final int? userId = Get.arguments?['userId'] as int?;

      if (userId != null) {
        // 加载指定用户信息
        final user = await _userRepository.getUserById(userId);
        if (user != null) {
          pageUser.value = user;

          // 判断是否是自己的主页
          isOwnProfile.value =
              userService.isLoggedIn.value &&
              userService.currentUser.value?.id == userId;

          // 如果已登录且不是自己的主页，检查是否已关注该用户
          if (userService.isLoggedIn.value && !isOwnProfile.value) {
            isFollowing.value = await _userFollowRepository.isFollowing(
              userService.currentUser.value!.id!,
              userId,
            );
          }

          await loadUserData();
        }
      } else {
        // 没有传递用户ID，显示当前登录用户
        if (userService.isLoggedIn.value) {
          pageUser.value = userService.currentUser.value;
          isOwnProfile.value = true;
          await loadUserData();
        } else {
          // 未登录状态，pageUser为空，显示登录按钮
          pageUser.value = null;
        }
      }
    }

    isLoading.value = false;
  }

  // 加载用户数据
  Future<void> loadUserData() async {
    if (pageUser.value?.id == null) return;

    int userId = pageUser.value!.id!;

    // 加载关注和粉丝数据
    followingCount.value = await _userFollowRepository.getFollowingCount(
      userId,
    );
    followersCount.value = await _userFollowRepository.getFollowerCount(userId);

    // 加载发布的陶瓷作品
    publishedCeramics.value = await _ceramicRepository.getUserCeramics(userId);

    // 加载收藏和点赞的陶瓷作品
    favoritedCeramics.value = await _ceramicInteractionRepository
        .getFavoritedCeramics(userId);
    likedCeramics.value = await _ceramicInteractionRepository.getLikedCeramics(
      userId,
    );

    try {
      // 加载收藏和点赞的视频
      favoritedVideos.value = await _videoInteractionRepository
          .getFavoritedVideos(userId);
      likedVideos.value = await _videoInteractionRepository.getLikedVideos(
        userId,
      );

      // 预加载一些内容的浏览用户数据
      // 为发布的陶瓷作品预加载浏览用户
      for (final ceramic in publishedCeramics) {
        if (ceramic.id != null) {
          loadContentViewedUsers(ceramic.id!, BrowseType.ceramic);
        }
      }

      // 为收藏的视频预加载浏览用户
      for (final video in favoritedVideos) {
        if (video.id != null) {
          loadContentViewedUsers(video.id!, BrowseType.video);
        }
      }

      // 为点赞的视频预加载浏览用户
      for (final video in likedVideos) {
        if (video.id != null) {
          loadContentViewedUsers(video.id!, BrowseType.video);
        }
      }
    } catch (e) {
      print('获取视频数据失败: $e');
      // 使用一些模拟数据
      favoritedVideos.value = [];
      likedVideos.value = [];
    }

    // 加载群组和聊天数据 (假设数据)
    groupsCount.value = await _chatRoomRepository.getGroupChatCount(userId);
    chatCount.value = await _chatRoomRepository.getPrivateChatCount(userId);
  }

  // 关注/取消关注用户
  Future<void> toggleFollow() async {
    if (pageUser.value?.id == null) return;

    final UserService userService = Get.find<UserService>();
    if (!userService.isLoggedIn.value) {
      // 未登录，提示登录
      userService.checkLoginThenExecute(
        loginRequiredMessage: 'You need to login to follow users',
        onLoggedIn: () => toggleFollow(),
      );
      return;
    }

    int currentUserId = userService.currentUser.value!.id!;
    int targetUserId = pageUser.value!.id!;

    // 不能关注自己
    if (currentUserId == targetUserId) return;

    // 更新关注状态
    if (isFollowing.value) {
      // 取消关注
      bool success = await _userFollowRepository.unfollowUser(
        followerId: currentUserId,
        followingId: targetUserId,
      );
      if (success) {
        isFollowing.value = false;
        followersCount.value--;
      }
    } else {
      // 关注用户
      final follow = await _userFollowRepository.followUser(
        followerId: currentUserId,
        followingId: targetUserId,
      );
      if (follow != null) {
        isFollowing.value = true;
        followersCount.value++;
      }
    }
  }

  // 跳转到登录页
  void goToLogin() {
    Get.toNamed(Routes.login);
  }

  // 跳转到设置页
  void goToSettings() {
    // 跳转到设置页面
    Get.toNamed(Routes.setup);
  }

  // 跳转到通知页
  void goToNotifications() {
    // 假设有通知路由
    Get.toNamed(Routes.notification);
  }

  // 跳转到通知页的指定标签
  void goToNotificationTab(int tabIndex) {
    Get.toNamed(Routes.notification, arguments: {'initialTabIndex': tabIndex});
  }

  // 跳转到关注列表
  void goToFollowers() {
    goToNotificationTab(2); // 对应notification页面中的"follow"标签
  }

  // 跳转到粉丝列表
  void goToFans() {
    goToNotificationTab(3); // 对应notification页面中的"fan"标签
  }

  // 跳转到群聊列表
  void goToGroups() {
    goToNotificationTab(1); // 对应notification页面中的"Group Chat"标签
  }

  // 跳转到私聊列表
  void goToChats() {
    goToNotificationTab(0); // 对应notification页面中的"Private Chat"标签
  }

  // 跳转到聊天页
  void goToChat() {
    if (pageUser.value?.id == null) return;

    // 获取用户服务
    final userService = Get.find<UserService>();
    final ChatRoomRepository _chatRoomRepository = ChatRoomRepository();

    // 检查登录状态并执行操作
    userService.checkLoginThenExecute(
      loginRequiredMessage: 'Please login to chat',
      onLoggedIn: () async {
        try {
          final currentUserId = userService.currentUser.value!.id!;
          final targetUserId = pageUser.value!.id!;

          // 不能和自己聊天
          if (currentUserId == targetUserId) {
            EasyLoading.showToast('You cannot chat with yourself');
            return;
          }

          // 查找或创建聊天室
          ChatRoom? chatRoom = await _chatRoomRepository.findPrivateChatRoom(
            currentUserId,
            targetUserId,
          );

          if (chatRoom == null) {
            // 创建新的聊天室
            chatRoom = ChatRoom(
              name:
                  pageUser.value!.nickname ??
                  pageUser.value!.username ??
                  'User',
              isGroup: false,
              memberIds: [currentUserId, targetUserId],
              lastMessage: '',
              lastMessageTime: DateTime.now(),
              createdAt: DateTime.now(),
              updatedAt: DateTime.now(),
            );

            final chatRoomId = await _chatRoomRepository.createChatRoom(
              chatRoom,
            );
            chatRoom = chatRoom.copyWith(id: chatRoomId);
          }

          // 跳转到聊天页面
          Get.toNamed(Routes.chat, arguments: {'chatRoom': chatRoom});
        } catch (e) {
          print('跳转到聊天页面失败: $e');
          EasyLoading.showToast('Failed to open chat, please try again later');
        }
      },
    );
  }

  // 跳转到个人资料页
  void goToPersonalData() {
    // 跳转到信息页面
    Get.toNamed(Routes.information);
  }

  // 举报用户
  void reportUser() {
    if (pageUser.value == null) return;

    final User user = pageUser.value!;

    ReportBottomSheet.show(
      onReport: (reason) async {
        // 这里可以实现实际的举报逻辑，如发送到服务器
        print('举报用户: ${user.id}, 原因: ${reason.toString()}');

        // 模拟API调用
        await Future.delayed(Duration(seconds: 1));

        // 返回true表示举报成功
        return true;
      },
    );
  }

  // 跳转到收藏视频详情页
  void goToFavoriteVideoDetail(int index) {
    // 记录浏览记录
    final video = favoritedVideos[index];
    if (video.id != null && pageUser.value?.id != null) {
      final record = BrowseRecord(
        userId: pageUser.value!.id!,
        contentId: video.id!,
        type: BrowseType.video,
        browseTime: DateTime.now(),
      );
      _browseRecordRepository.addBrowseRecord(record);
    }

    // 跳转到视频详情页，传递来源和初始索引
    Get.toNamed(
      Routes.videoDetail,
      arguments: {'source': 'favorites', 'initialIndex': index},
    );
  }

  // 跳转到点赞视频详情页
  void goToLikedVideoDetail(int index) {
    // 记录浏览记录
    final video = likedVideos[index];
    if (video.id != null && pageUser.value?.id != null) {
      final record = BrowseRecord(
        userId: pageUser.value!.id!,
        contentId: video.id!,
        type: BrowseType.video,
        browseTime: DateTime.now(),
      );
      _browseRecordRepository.addBrowseRecord(record);
    }

    // 跳转到视频详情页，传递来源和初始索引
    Get.toNamed(
      Routes.videoDetail,
      arguments: {'source': 'likes', 'initialIndex': index},
    );
  }

  // 强制刷新数据
  void forceRefresh() {
    print('强制刷新Me页面数据');
    // 重置页面状态
    isFromNavBar.value = Get.arguments?['fromNavBar'] ?? true;
    // 重新加载数据
    initData();
    update(["me"]);
  }

  @override
  void onInit() {
    super.onInit();
    tabController = TabController(length: 3, vsync: this);

    // 设置初始选中标签
    tabController.index = 0;

    // 确定是否从导航栏进入
    isFromNavBar.value = Get.arguments?['fromNavBar'] ?? true;

    // 注册为观察者
    CeramicInteractionRepository.addObserver(this);
    VideoInteractionRepository.addObserver(this);
    UserFollowRepository.addObserver(this);
    RecommendedVideoRepository.addObserver(this);
    CeramicRepository.addObserver(this);
    OfficialContentRepository.addObserver(this);

    // 立即初始化数据
    initData();

    // 添加页面重新获得焦点的监听
    ever(Get.find<UserService>().isLoggedIn, (_) {
      // 当登录状态变化时，重新加载数据
      initData();
    });

    // 监听路由参数，如果有forceRefresh参数，则强制刷新
    if (Get.arguments?['forceRefresh'] == true) {
      forceRefresh();
    }
  }

  @override
  void onReady() {
    super.onReady();
    // 在页面准备好后设置路由监听器，以便在页面恢复时刷新数据
    if (Get.context != null) {
      final route = ModalRoute.of(Get.context!);
      if (route != null) {
        routeObserver.subscribe(this, route);
        print('已订阅路由观察器');
      } else {
        print('路由为空，无法订阅路由观察器');
        // 延迟尝试订阅
        Future.delayed(Duration(milliseconds: 500), () {
          final delayedRoute = ModalRoute.of(Get.context!);
          if (delayedRoute != null) {
            routeObserver.subscribe(this, delayedRoute);
            print('延迟订阅路由观察器成功');
          }
        });
      }
    } else {
      print('上下文为空，无法订阅路由观察器');
    }
  }

  // 当页面从被覆盖变为可见时（例如从登录页面返回）重新加载数据
  void didPopNext() {
    print('Me页面重新获得焦点');

    // 检查当前页面是否显示的是当前登录用户
    if (isOwnProfile.value) {
      // 获取UserService中的最新用户信息
      final UserService userService = Get.find<UserService>();
      if (userService.isLoggedIn.value &&
          userService.currentUser.value != null) {
        // 更新pageUser以反映最新的用户信息
        pageUser.value = userService.currentUser.value;
      }
    }

    // 重新加载所有数据
    initData();
    update(["me"]);
  }

  @override
  void onClose() {
    // 取消路由订阅
    routeObserver.unsubscribe(this);
    // 取消注册观察者
    CeramicInteractionRepository.removeObserver(this);
    VideoInteractionRepository.removeObserver(this);
    UserFollowRepository.removeObserver(this);
    RecommendedVideoRepository.removeObserver(this);
    CeramicRepository.removeObserver(this);
    OfficialContentRepository.removeObserver(this);
    tabController.dispose();
    super.onClose();
  }

  // RouteAware接口需要实现的方法
  @override
  void didPush() {
    // 路由被推入
    print('Me页面被推入');
    // 初始化数据，确保从其他页面跳转过来时能正确加载数据
    initData();
  }

  @override
  void didPushNext() {
    // 有新路由被推到上面
    print('Me页面被覆盖');
  }

  @override
  void didPop() {
    // 当前路由被弹出
    print('Me页面被弹出');
  }

  // 检查视频是否被收藏
  bool isVideoFavorited(int videoId) {
    return favoritedVideos.any((video) => video.id == videoId);
  }

  // 检查视频是否被点赞
  bool isVideoLiked(int videoId) {
    return likedVideos.any((video) => video.id == videoId);
  }

  // 检查陶瓷作品是否被收藏
  bool isCeramicFavorited(int ceramicId) {
    return favoritedCeramics.any((ceramic) => ceramic.id == ceramicId);
  }

  // 检查陶瓷作品是否被点赞
  bool isCeramicLiked(int ceramicId) {
    return likedCeramics.any((ceramic) => ceramic.id == ceramicId);
  }

  // 视频收藏/取消收藏
  Future<bool> toggleVideoFavorite(RecommendedVideo video) async {
    if (video.id == null) return false;

    final UserService userService = Get.find<UserService>();
    if (!userService.isLoggedIn.value) {
      userService.checkLoginThenExecute(
        loginRequiredMessage: 'You need to login to favorite this video',
        onLoggedIn: () => toggleVideoFavorite(video),
      );
      return false;
    }

    int userId = userService.currentUser.value!.id!;
    int videoId = video.id!;

    bool isFavorited = isVideoFavorited(videoId);
    bool success = false;

    if (isFavorited) {
      // 取消收藏
      success = await _videoInteractionRepository.unfavoriteVideo(
        userId,
        videoId,
      );
      if (success) {
        // 从收藏列表中移除
        favoritedVideos.removeWhere((v) => v.id == videoId);

        // 创建新的副本以触发响应式更新
        final newList = <RecommendedVideo>[];
        newList.addAll(favoritedVideos);
        favoritedVideos.value = newList;

        // 通知UI更新
        update(["me"]);
      }
    } else {
      // 添加收藏
      success = await _videoInteractionRepository.favoriteVideo(
        userId,
        videoId,
      );
      if (success) {
        // 确保列表中没有重复项
        if (!favoritedVideos.any((v) => v.id == videoId)) {
          final newList = <RecommendedVideo>[];
          newList.addAll(favoritedVideos);
          newList.add(video);
          favoritedVideos.value = newList;
        }
        // 通知UI更新
        update(["me"]);
      }
    }

    return success ? !isFavorited : isFavorited;
  }

  // 视频点赞/取消点赞
  Future<bool> toggleVideoLike(RecommendedVideo video) async {
    if (video.id == null) return false;

    final UserService userService = Get.find<UserService>();
    if (!userService.isLoggedIn.value) {
      userService.checkLoginThenExecute(
        loginRequiredMessage: 'You need to login to like this video',
        onLoggedIn: () => toggleVideoLike(video),
      );
      return false;
    }

    int userId = userService.currentUser.value!.id!;
    int videoId = video.id!;

    bool isLiked = isVideoLiked(videoId);
    bool success = false;

    if (isLiked) {
      // 取消点赞
      success = await _videoInteractionRepository.unlikeVideo(userId, videoId);
      if (success) {
        // 从点赞列表中移除
        likedVideos.removeWhere((v) => v.id == videoId);

        // 创建新的副本以触发响应式更新
        final newList = <RecommendedVideo>[];
        newList.addAll(likedVideos);
        likedVideos.value = newList;

        // 通知UI更新
        update(["me"]);
      }
    } else {
      // 添加点赞
      success = await _videoInteractionRepository.likeVideo(userId, videoId);
      if (success) {
        // 确保列表中没有重复项
        if (!likedVideos.any((v) => v.id == videoId)) {
          final newList = <RecommendedVideo>[];
          newList.addAll(likedVideos);
          newList.add(video);
          likedVideos.value = newList;
        }
        // 通知UI更新
        update(["me"]);
      }
    }

    return success ? !isLiked : isLiked;
  }

  // 陶瓷作品收藏/取消收藏
  Future<bool> toggleCeramicFavorite(Ceramic ceramic) async {
    if (ceramic.id == null) return false;

    final UserService userService = Get.find<UserService>();
    if (!userService.isLoggedIn.value) {
      userService.checkLoginThenExecute(
        loginRequiredMessage: 'You need to login to favorite this ceramic work',
        onLoggedIn: () => toggleCeramicFavorite(ceramic),
      );
      return false;
    }

    int userId = userService.currentUser.value!.id!;
    int ceramicId = ceramic.id!;

    bool isFavorited = isCeramicFavorited(ceramicId);
    bool success = false;

    if (isFavorited) {
      // 取消收藏
      success = await _ceramicInteractionRepository.unfavoriteCeramic(
        userId,
        ceramicId,
      );
      if (success) {
        // 从收藏列表中移除
        favoritedCeramics.removeWhere((c) => c.id == ceramicId);

        // 创建新的副本以触发响应式更新
        final newList = <Ceramic>[];
        newList.addAll(favoritedCeramics);
        favoritedCeramics.value = newList;

        // 通知UI更新
        update(["me"]);
      }
    } else {
      // 添加收藏
      success = await _ceramicInteractionRepository.favoriteCeramic(
        userId,
        ceramicId,
      );
      if (success) {
        // 确保列表中没有重复项
        if (!favoritedCeramics.any((c) => c.id == ceramicId)) {
          final newList = <Ceramic>[];
          newList.addAll(favoritedCeramics);
          newList.add(ceramic);
          favoritedCeramics.value = newList;
        }
        // 通知UI更新
        update(["me"]);
      }
    }

    return success ? !isFavorited : isFavorited;
  }

  // 陶瓷作品点赞/取消点赞
  Future<bool> toggleCeramicLike(Ceramic ceramic) async {
    if (ceramic.id == null) return false;

    final UserService userService = Get.find<UserService>();
    if (!userService.isLoggedIn.value) {
      userService.checkLoginThenExecute(
        loginRequiredMessage: 'You need to login to like this ceramic work',
        onLoggedIn: () => toggleCeramicLike(ceramic),
      );
      return false;
    }

    int userId = userService.currentUser.value!.id!;
    int ceramicId = ceramic.id!;

    bool isLiked = isCeramicLiked(ceramicId);
    bool success = false;

    if (isLiked) {
      // 取消点赞
      success = await _ceramicInteractionRepository.unlikeCeramic(
        userId,
        ceramicId,
      );
      if (success) {
        // 从点赞列表中移除
        likedCeramics.removeWhere((c) => c.id == ceramicId);

        // 创建新的副本以触发响应式更新
        final newList = <Ceramic>[];
        newList.addAll(likedCeramics);
        likedCeramics.value = newList;

        // 通知UI更新
        update(["me"]);
      }
    } else {
      // 添加点赞
      success = await _ceramicInteractionRepository.likeCeramic(
        userId,
        ceramicId,
      );
      if (success) {
        // 确保列表中没有重复项
        if (!likedCeramics.any((c) => c.id == ceramicId)) {
          final newList = <Ceramic>[];
          newList.addAll(likedCeramics);
          newList.add(ceramic);
          likedCeramics.value = newList;
        }
        // 通知UI更新
        update(["me"]);
      }
    }

    return success ? !isLiked : isLiked;
  }

  // 实现CeramicInteractionObserver接口
  @override
  void onLikeStatusChanged(int userId, int ceramicId, bool isLiked) {
    // 判断当前页面的用户与交互的用户是否相同
    if (pageUser.value?.id == userId) {
      // 如果用户取消了点赞，从点赞列表中删除
      if (!isLiked) {
        likedCeramics.removeWhere((ceramic) => ceramic.id == ceramicId);
      } else {
        // 如果是新点赞并且点赞列表中不存在
        if (!likedCeramics.any((c) => c.id == ceramicId)) {
          // 查找陶瓷数据以添加到点赞列表
          _addCeramicToLikedList(ceramicId);
        }
      }

      // 更新列表中现有陶瓷的点赞状态
      _updateCeramicLikeStatus(ceramicId, isLiked);
      update(["me"]);
    }
  }

  @override
  void onFavoriteStatusChanged(int userId, int ceramicId, bool isFavorited) {
    // 判断当前页面的用户与交互的用户是否相同
    if (pageUser.value?.id == userId) {
      // 如果用户取消了收藏，从收藏列表中删除
      if (!isFavorited) {
        favoritedCeramics.removeWhere((ceramic) => ceramic.id == ceramicId);
      } else {
        // 如果是新收藏并且收藏列表中不存在
        if (!favoritedCeramics.any((c) => c.id == ceramicId)) {
          // 查找陶瓷数据以添加到收藏列表
          _addCeramicToFavoriteList(ceramicId);
        }
      }

      // 更新列表中现有陶瓷的收藏状态
      _updateCeramicFavoriteStatus(ceramicId, isFavorited);
      update(["me"]);
    }
  }

  // 辅助方法：添加陶瓷到点赞列表
  Future<void> _addCeramicToLikedList(int ceramicId) async {
    try {
      final ceramic = await _ceramicRepository.getCeramicById(ceramicId);
      if (ceramic != null && !likedCeramics.any((c) => c.id == ceramicId)) {
        likedCeramics.add(ceramic);
      }
    } catch (e) {
      print('添加陶瓷到点赞列表失败: $e');
    }
  }

  // 辅助方法：添加陶瓷到收藏列表
  Future<void> _addCeramicToFavoriteList(int ceramicId) async {
    try {
      final ceramic = await _ceramicRepository.getCeramicById(ceramicId);
      if (ceramic != null && !favoritedCeramics.any((c) => c.id == ceramicId)) {
        favoritedCeramics.add(ceramic);
      }
    } catch (e) {
      print('添加陶瓷到收藏列表失败: $e');
    }
  }

  // 辅助方法：更新列表中陶瓷的点赞状态
  void _updateCeramicLikeStatus(int ceramicId, bool isLiked) {
    // 更新已发布的陶瓷
    int publishedIndex = publishedCeramics.indexWhere((c) => c.id == ceramicId);
    if (publishedIndex != -1) {
      final ceramic = publishedCeramics[publishedIndex];
      publishedCeramics[publishedIndex] = ceramic.copyWith(
        likeCount: isLiked ? ceramic.likeCount + 1 : ceramic.likeCount - 1,
      );
    }
  }

  // 辅助方法：更新列表中陶瓷的收藏状态
  void _updateCeramicFavoriteStatus(int ceramicId, bool isFavorited) {
    // 更新已发布的陶瓷
    int publishedIndex = publishedCeramics.indexWhere((c) => c.id == ceramicId);
    if (publishedIndex != -1) {
      final ceramic = publishedCeramics[publishedIndex];
      publishedCeramics[publishedIndex] = ceramic.copyWith(
        favoriteCount:
            isFavorited ? ceramic.favoriteCount + 1 : ceramic.favoriteCount - 1,
      );
    }
  }

  // 实现VideoInteractionObserver接口
  @override
  void onVideoLikeStatusChanged(int userId, int videoId, bool isLiked) {
    // 判断当前页面的用户与交互的用户是否相同
    if (pageUser.value?.id == userId) {
      // 如果用户取消了点赞，从点赞列表中删除
      if (!isLiked) {
        likedVideos.removeWhere((video) => video.id == videoId);
      } else {
        // 如果是新点赞并且点赞列表中不存在
        if (!likedVideos.any((v) => v.id == videoId)) {
          // 查找视频数据以添加到点赞列表
          _addVideoToLikedList(videoId);
        }
      }

      // 更新列表中视频的点赞计数
      _updateVideoCount(videoId, isLiked: isLiked);
      update(["me"]);
    }
  }

  @override
  void onVideoFavoriteStatusChanged(int userId, int videoId, bool isFavorited) {
    // 判断当前页面的用户与交互的用户是否相同
    if (pageUser.value?.id == userId) {
      // 如果用户取消了收藏，从收藏列表中删除
      if (!isFavorited) {
        favoritedVideos.removeWhere((video) => video.id == videoId);
      } else {
        // 如果是新收藏并且收藏列表中不存在
        if (!favoritedVideos.any((v) => v.id == videoId)) {
          // 查找视频数据以添加到收藏列表
          _addVideoToFavoriteList(videoId);
        }
      }

      // 更新列表中视频的收藏计数
      _updateVideoCount(videoId, isFavorited: isFavorited);
      update(["me"]);
    }
  }

  // 辅助方法：添加视频到点赞列表
  Future<void> _addVideoToLikedList(int videoId) async {
    try {
      final video = await _videoInteractionRepository
          .getLikedVideos(pageUser.value!.id!)
          .then(
            (videos) => videos.firstWhere(
              (v) => v.id == videoId,
              orElse: () => throw Exception('视频未找到'),
            ),
          );

      if (!likedVideos.any((v) => v.id == videoId)) {
        likedVideos.add(video);
      }
    } catch (e) {
      print('添加视频到点赞列表失败: $e');
    }
  }

  // 辅助方法：添加视频到收藏列表
  Future<void> _addVideoToFavoriteList(int videoId) async {
    try {
      final video = await _videoInteractionRepository
          .getFavoritedVideos(pageUser.value!.id!)
          .then(
            (videos) => videos.firstWhere(
              (v) => v.id == videoId,
              orElse: () => throw Exception('视频未找到'),
            ),
          );

      if (!favoritedVideos.any((v) => v.id == videoId)) {
        favoritedVideos.add(video);
      }
    } catch (e) {
      print('添加视频到收藏列表失败: $e');
    }
  }

  // 辅助方法：更新视频计数
  void _updateVideoCount(int videoId, {bool? isLiked, bool? isFavorited}) {
    // 更新已有视频的点赞数或收藏数
    for (int i = 0; i < likedVideos.length; i++) {
      if (likedVideos[i].id == videoId && isLiked != null) {
        likedVideos[i] = likedVideos[i].copyWith(
          likeCount:
              isLiked
                  ? likedVideos[i].likeCount + 1
                  : likedVideos[i].likeCount - 1,
        );
      }
    }

    for (int i = 0; i < favoritedVideos.length; i++) {
      if (favoritedVideos[i].id == videoId && isFavorited != null) {
        favoritedVideos[i] = favoritedVideos[i].copyWith(
          favoriteCount:
              isFavorited
                  ? favoritedVideos[i].favoriteCount + 1
                  : favoritedVideos[i].favoriteCount - 1,
        );
      }
    }
  }

  // 加载内容浏览用户
  Future<void> loadContentViewedUsers(int contentId, BrowseType type) async {
    // 生成唯一键
    final String key = '${type.name}_$contentId';

    // 初始化loading状态
    if (!contentUsersLoading.containsKey(key)) {
      contentUsersLoading[key] = false.obs;
    }

    // 避免重复加载
    if (contentUsersLoading[key]!.value) return;

    contentUsersLoading[key]!.value = true;

    try {
      final users = await _browseRecordRepository.getViewedUsersByContent(
        contentId,
        type,
        limit: 4,
      );

      if (!contentViewedUsers.containsKey(key)) {
        contentViewedUsers[key] = <User>[].obs;
      }

      contentViewedUsers[key]!.value = users;
    } catch (e) {
      debugPrint('加载内容浏览用户失败: $e');
    } finally {
      contentUsersLoading[key]!.value = false;
    }
  }

  // 获取内容浏览用户
  List<User> getContentViewedUsers(int contentId, BrowseType type) {
    final String key = '${type.name}_$contentId';
    if (!contentViewedUsers.containsKey(key)) {
      return [];
    }
    return contentViewedUsers[key]!;
  }

  // 判断内容浏览用户是否加载中
  bool isContentUsersLoading(int contentId, BrowseType type) {
    final String key = '${type.name}_$contentId';
    if (!contentUsersLoading.containsKey(key)) {
      return false;
    }
    return contentUsersLoading[key]!.value;
  }

  // 实现UserFollowObserver接口
  @override
  void onFollowStatusChanged(
    int followerId,
    int followingId,
    bool isFollowing,
  ) {
    // 如果当前页面显示的是关注者或被关注者，更新统计数据
    if (pageUser.value != null) {
      // 如果当前用户是关注者，更新关注数量
      if (pageUser.value!.id == followerId) {
        _refreshFollowingCount();
      }

      // 如果当前用户是被关注者，更新粉丝数量
      if (pageUser.value!.id == followingId) {
        _refreshFollowersCount();
      }
    }
  }

  // 刷新关注数量
  Future<void> _refreshFollowingCount() async {
    if (pageUser.value?.id != null) {
      followingCount.value = await _userFollowRepository.getFollowingCount(
        pageUser.value!.id!,
      );
      update(["me"]);
    }
  }

  // 刷新粉丝数量
  Future<void> _refreshFollowersCount() async {
    if (pageUser.value?.id != null) {
      followersCount.value = await _userFollowRepository.getFollowerCount(
        pageUser.value!.id!,
      );
      update(["me"]);
    }
  }

  // 实现VideoDeleteObserver接口
  @override
  void onVideoDeleted(int videoId) {
    // 从收藏视频列表中移除被删除的视频
    favoritedVideos.removeWhere((video) => video.id == videoId);

    // 从点赞视频列表中移除被删除的视频
    likedVideos.removeWhere((video) => video.id == videoId);

    // 更新UI
    update(["me"]);
  }

  // 实现CeramicDeleteObserver接口
  @override
  void onCeramicDeleted(int ceramicId) {
    // 从收藏陶瓷作品列表中移除被删除的作品
    favoritedCeramics.removeWhere((ceramic) => ceramic.id == ceramicId);

    // 从点赞陶瓷作品列表中移除被删除的作品
    likedCeramics.removeWhere((ceramic) => ceramic.id == ceramicId);

    // 从发布的陶瓷作品列表中移除被删除的作品
    publishedCeramics.removeWhere((ceramic) => ceramic.id == ceramicId);

    // 更新UI
    update(["me"]);
  }

  // 实现OfficialContentDeleteObserver接口
  @override
  void onOfficialContentDeleted(int contentId) {
    // 从收藏官方内容列表中移除被删除的内容
    favoritedOfficialContents.removeWhere((content) => content.id == contentId);

    // 从点赞官方内容列表中移除被删除的内容
    likedOfficialContents.removeWhere((content) => content.id == contentId);

    // 更新UI
    update(["me"]);
  }
}
